package com.zhupf.part7;

/**
 * @author zhupf
 * @date 2023年11月14日 9:36
 * @Description
 *
 * 21、合并两个有序链表
 *
 */
public class MergeTwoLists {
    public static void main(String[] args) {
//        ListNode list1 = new ListNode(1,new ListNode(2,new ListNode(4)));
//        ListNode list2 = new ListNode(1,new ListNode(3,new ListNode(4)));
        ListNode list1 = new ListNode(1);
        ListNode list2 = new ListNode(2);
        mergeTwoLists(list1, list2);
    }

    public static ListNode mergeTwoLists3(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }else if (list1.val < list2.val){
             list1.next = mergeTwoLists3(list1.next,list2);
            return list1;
        }else {
            list2.next = mergeTwoLists3(list1,list2.next);
            return list2;
        }
    }

    public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        ListNode pre = new ListNode(-1);
        ListNode result = pre;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                pre.next = list1;
                list1 = list1.next;
            } else {
                pre.next = list2;
                list2 = list2.next;
            }
            pre = pre.next;
        }
        pre.next = list1 == null ? list2 : list1;
        return result.next;
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null) {
            return null;
        }
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        ListNode node1 = list1.val < list2.val ? list1 : list2;
        ListNode node2 = list1.val >= list2.val ? list1 : list2;
        ListNode result = node1;
        while (node1 != null) {
            if (node1.next == null) {
                node1.next = node2;
                break;
            }
            ListNode t1 = node1.next;
            while (node2 != null && t1.val >= node2.val) {
                ListNode t = node2.next;
                node1.next = node2;
                node2 = t;
                node1 = node1.next;
            }
            node1.next = t1;
            node1 = t1;
            if (node2 == null) {
                break;
            }
        }
        return result;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
